/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-5-27 下午6:10 Created by dwzhang
 */
package com.jade.modules.media.impl;

import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.sql.SqlUtils;
import com.jade.framework.base.util.PagingList;
import com.jade.modules.media.CMediaItem;
import com.jade.modules.media.MediaException;
import com.jade.modules.media.CMediaItem;
import com.jade.modules.media.MediaItemDao;

/**
 * 采用JPA方式实现的接口。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-5-27 下午6:10
 */
//@Named ("module_mediaItemDao")
public class JpaItemDao implements MediaItemDao
{
    protected static final String SQL_QUERY = "SELECT item FROM com.jade.modules.media.CMediaItem item";
    @PersistenceContext (unitName = "default")
    protected EntityManager entityManager;

    public CMediaItem getItem(long itemId)
    {
        return entityManager.find(CMediaItem.class, itemId);
    }

    public CMediaItem getItemByUri(String uri)
    {
        String sql = "SELECT item FROM com.jade.modules.media.CMediaItem item WHERE uri=:uri";
        Query query = entityManager.createQuery(sql);
        query.setParameter("uri", uri);
        return SqlUtils.getSingleResult(query);
    }

    public void addItem(CMediaItem item)
            throws MediaException
    {
        entityManager.persist(item);
    }

    public void removeItem(CMediaItem item)
            throws MediaException
    {
        CMediaItem old = getItem(item.getId());
        if (old != null) {
            entityManager.remove(old);
        }
    }

    public PagingList<CMediaItem> query(Criteria criteria)
    {
        return SqlUtils.sqlQuery(SQL_QUERY, entityManager, criteria);
    }
}
